#!/usr/bin/python
import sys
import os
import wx

import cProfile
import multiprocessing

import slice
import parseSTL

res = 0.25
layer = 0
filename = ""
S = slice.slicer([], 0, 0)
S.setResolution(res)
	
class dragDrop(wx.FileDropTarget):
	def __init__(self,parent, obj):
		self.parent = parent
		wx.FileDropTarget.__init__(self)
	
	def OnDropFiles(self,x,y,filenames):
		global filename
		""" Select last file in case of multiple files, in future maybe support multiple files"""
		for name in filenames:
			filename = name
		DOIT()
		self.parent.Refresh()
		
class drawPanel(wx.Panel):
	def __init__(self, parent, *args, **kwargs):
		wx.Panel.__init__(self,parent,*args,**kwargs)
		self.parent = parent
		self.Bind(wx.EVT_PAINT, self.onPaint)
		self.Bind(wx.EVT_MOUSEWHEEL, self.onScroll)
		
		
	def onPaint(self,event):
		global S
		offx = 100
		offy = 100
		scale = 2
		dc = wx.PaintDC(event.GetEventObject())
		dc.Clear()
		dc.SetPen(wx.Pen("BLACK", 2))
		temp = S.getSlice(layer*S.getResolution())
		for i in range(len(temp)):
			tmp = temp[i]
			if(tmp):
				if (tmp[4] == 2):
					dc.DrawLine(scale*tmp[0][0]+offx,scale*tmp[0][1]+offy,scale*tmp[1][0]+offx,scale*tmp[1][1]+offy)
				else:
					dc.DrawLine(scale*tmp[0][0]+offx,scale*tmp[0][1]+offy,scale*tmp[1][0]+offx,scale*tmp[1][1]+offy)
					dc.DrawLine(scale*tmp[1][0]+offx,scale*tmp[1][1]+offy,scale*tmp[2][0]+offx,scale*tmp[2][1]+offy)
					dc.DrawLine(scale*tmp[2][0]+offx,scale*tmp[2][1]+offy,scale*tmp[0][0]+offx,scale*tmp[0][1]+offy)
					
	def onScroll(self,event):
		global layer
		direction = event.GetWheelRotation()
		if direction > 0:
			if layer < S.getMax()/S.getResolution():
				layer += 1
			
		else:
			if layer > S.getMin()/S.getResolution():
				layer -= 1
		self.parent.control.SetValue(str(layer*res))
		self.Refresh()
		
class menuBar(wx.MenuBar):
	def __init__(self, parent):

		wx.MenuBar.__init__(self, 0)
		self.parent = parent
		filemenu = wx.Menu()
		menuOpen = filemenu.Append(wx.ID_OPEN, "&Open", "Open a file")
		filemenu.AppendSeparator()
		menuExit = filemenu.Append(wx.ID_EXIT, "E&xit", "Exit")

		helpmenu = wx.Menu()
		menuAbout = helpmenu.Append(wx.ID_ABOUT, "&About", "About")
		menuHelp = helpmenu.Append(wx.ID_HELP, "&Help", "Help")

		menubar = wx.MenuBar()
		menubar.Append(filemenu,"&File")
		menubar.Append(helpmenu,"&Help")
		self.parent.SetMenuBar(menubar)

		self.parent.Bind(wx.EVT_MENU, self.OnAbout, menuAbout)
		self.parent.Bind(wx.EVT_MENU, self.OnHelp, menuHelp)
		self.parent.Bind(wx.EVT_MENU, self.OnOpen, menuOpen)
		self.parent.Bind(wx.EVT_MENU, self.OnExit, menuExit)
		self.parent.Bind(wx.EVT_CLOSE, self.OnExit)
		
	def OnAbout(self, event):
		dlg = wx.MessageDialog(self, "A crappy slicer\ngannon - April 2012", "About", wx.OK)
		dlg.ShowModal()
		dlg.Destroy()

	def OnHelp(self, event):
		dlg = wx.MessageDialog(self, "There will be no help herp", "Help", wx.OK)
		dlg.ShowModal()
		dlg.Destroy()

	def OnOpen(self, event):
		global filename
		self.dirname=''
		dlg = wx.FileDialog(self.parent,"Choose a file", self.dirname, "", "*.stl", wx.OPEN)
		if dlg.ShowModal() == wx.ID_OK:
			self.filename = dlg.GetFilename()
			self.dirname = dlg.GetDirectory()
			filename = os.path.join(self.dirname,self.filename)
			DOIT()
			self.parent.Refresh()
		dlg.Destroy()

	def OnExit(self, event):
		dlg = wx.MessageDialog(self, "Do you really want to close this application?","Confirm Exit", wx.OK|wx.CANCEL|wx.ICON_QUESTION)
		result = dlg.ShowModal()
		dlg.Destroy()
		if result == wx.ID_OK:
			exit(0)
		
		
class MainWindow(wx.Frame):
	def __init__(self, parent, title, size):
		
		wx.Frame.__init__(self,parent,title=title,size=size)
		self.CreateStatusBar()

		self.control = wx.TextCtrl(self, size=(400,300), style=wx.TE_MULTILINE | wx.TE_READONLY)
		
		self.panel = drawPanel(self, size=(400,300))
		
		hbox = wx.BoxSizer(wx.HORIZONTAL)
		self.slider = wx.Slider(self, -1, 0, 0, 100, (-1, -1), (25, 90), wx.VERTICAL | wx.SL_LABELS | wx.SL_INVERSE)

		hbox.Add(self.panel, 0,  wx.LEFT | wx.TOP)
		hbox.Add(self.slider, 0, wx.LEFT | wx.TOP)
		
		dt = dragDrop(self,parent)
		self.SetDropTarget(dt)

		menuBar(self)

		self.Bind(wx.EVT_SLIDER, self.sliderUpdate)
		
		self.sizer = wx.BoxSizer(wx.HORIZONTAL)
		self.sizer.Add(self.control,1,wx.EXPAND)
		self.sizer.Add(hbox,1,wx.EXPAND)
		self.SetSizer(self.sizer)
		self.SetAutoLayout(1)
		self.sizer.Fit(self)

		self.Show(True)
	def sliderUpdate(self,event):
		global height
		global layer
		layer = ((height/res)/100)*self.slider.GetValue()
		self.control.SetValue(str(layer*res))
		self.Refresh()
	
P = parseSTL.parseSTL()
def DOIT():
	global t1
	global t2
	global T
	global filename
	global S
	global height
	global P
	if (filename == ""):
		return
	P.setFile(filename)
	P.parseFile()
	T=P.getTriangles()
	print 'Triangles: ', len(T)
	print 'CPUS: ',multiprocessing.cpu_count()
	
	minVertex = P.getMin()
	maxVertex = P.getMax()
	height = maxVertex - minVertex
	print 'height: ', height
	print 'Slices: ', height/res
	S = slice.slicer(T, minVertex, maxVertex)
	S.setResolution(res)
	#S.sliceAll()
	#S.sliceAllThreaded()
	cProfile.run('S.sliceAll()')
	

DOIT()
app = wx.App(False)
frame = wx.Frame(None, wx.ID_ANY, "Slicer")
frame = MainWindow(None, "Slicer", (800,600))
app.MainLoop()
